const express = require('express');
const path = require('path');
const fs = require('fs');

const app = express();
const PORT = 8009;

// 中间件
app.use(express.json());
app.use(express.static(path.join(__dirname, 'renderer')));

// 模拟数据存储
let articles = [];
let settings = {
    ai_provider: 'aliyun',
    api_key: 'sk-657dfa6311a84dd392d706528b6449a8',
    api_base_url: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
    default_style: 'professional',
    default_length: 'normal',
    auto_save: 'true',
    theme: 'light'
};
let topics = [];

// AI服务配置
const AI_CONFIGS = {
    openai: {
        baseURL: 'https://api.openai.com/v1',
        model: 'gpt-3.5-turbo',
        headers: (apiKey) => ({
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json'
        })
    },
    deepseek: {
        baseURL: 'https://api.deepseek.com/v1',
        model: 'deepseek-chat',
        headers: (apiKey) => ({
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json'
        })
    },
    openrouter: {
        baseURL: 'https://openrouter.ai/api/v1',
        model: 'deepseek/deepseek-chat',
        headers: (apiKey) => ({
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json',
            'HTTP-Referer': 'https://ai2word.app',
            'X-Title': 'AI2Word'
        })
    },
    aliyun: {
        baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
        model: 'deepseek-v3.1',
        headers: (apiKey) => ({
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json'
        })
    },
    claude: {
        baseURL: 'https://api.anthropic.com/v1',
        model: 'claude-3-sonnet-20240229',
        headers: (apiKey) => ({
            'x-api-key': apiKey,
            'Content-Type': 'application/json',
            'anthropic-version': '2023-06-01'
        })
    }
};

// AI调用函数
async function callAI(prompt, provider = 'aliyun', apiKey = null) {
    const config = AI_CONFIGS[provider];
    if (!config) {
        throw new Error(`不支持的AI提供商: ${provider}`);
    }
    
    const actualApiKey = apiKey || settings.api_key;
    if (!actualApiKey) {
        throw new Error('请配置API密钥');
    }
    
    const baseURL = settings.api_base_url || config.baseURL;
    
    try {
        const axios = require('axios');
        
        let requestData;
        let endpoint;
        
        if (provider === 'claude') {
            endpoint = `${baseURL}/messages`;
            requestData = {
                model: config.model,
                max_tokens: 4000,
                messages: [
                    {
                        role: 'user',
                        content: prompt
                    }
                ]
            };
        } else if (provider === 'aliyun') {
            endpoint = `${baseURL}/chat/completions`;
            requestData = {
                model: config.model,
                messages: [
                    {
                        role: 'user',
                        content: prompt
                    }
                ],
                max_tokens: 4000,
                temperature: 0.7
            };
        } else {
            endpoint = `${baseURL}/chat/completions`;
            requestData = {
                model: config.model,
                messages: [
                    {
                        role: 'user',
                        content: prompt
                    }
                ],
                max_tokens: 4000,
                temperature: 0.7
            };
        }
        
        const response = await axios.post(endpoint, requestData, {
            headers: config.headers(actualApiKey),
            timeout: 60000
        });
        
        if (provider === 'claude') {
            return response.data.content[0].text;
        } else if (provider === 'aliyun') {
            // 阿里云百炼API返回格式
            const content = response.data.choices[0].message.content;
            
            // 检查是否有思考过程
            if (response.data.choices[0].message.reasoning_content) {
                console.log("思考过程:", response.data.choices[0].message.reasoning_content);
            }
            
            return content;
        } else {
            // OpenAI格式 (包括OpenRouter)
            return response.data.choices[0].message.content;
        }
    } catch (error) {
        console.error('AI调用失败:', error.response?.data || error.message);
        throw new Error(`AI调用失败: ${error.response?.data?.error?.message || error.message}`);
    }
}

// 路由
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'renderer', 'index.html'));
});

// API 路由
app.post('/api/generate-topics', async (req, res) => {
    try {
        console.log('收到生成主题请求:', req.body);
        
        const { preferences } = req.body;
        
        const prompt = `作为一个技术博客专家，请为微信公众号推荐5个热门的技术文章主题。要求：
1. 主题应该是当前热门的技术话题
2. 适合技术人员阅读
3. 涵盖前端、后端、AI、云计算等领域
4. 每个主题都应该具有实用性和时效性

请直接返回5个主题标题，每行一个，不需要编号或其他格式。`;

        try {
            const aiResponse = await callAI(prompt, settings.ai_provider, settings.api_key);
            
            // 解析AI返回的主题
            const topicTitles = aiResponse.split('\n')
                .map(line => line.trim())
                .filter(line => line && !line.match(/^\d+\.?/))
                .slice(0, 5);
            
            const generatedTopics = topicTitles.map((title, index) => ({
                id: Date.now() + index,
                title: title,
                source: 'ai_generated',
                created_at: new Date().toISOString()
            }));
            
            // 保存到topics数组
            topics.push(...generatedTopics);
            
            res.json({ success: true, data: generatedTopics });
        } catch (aiError) {
            console.error('AI生成主题失败，使用备用主题:', aiError);
            
            // 如果AI调用失败，返回备用主题
            const fallbackTopics = [
                {
                    id: Date.now() + 1,
                    title: 'Vue 3.4 新特性详解与实战应用',
                    source: 'ai_generated',
                    created_at: new Date().toISOString()
                },
                {
                    id: Date.now() + 2,
                    title: 'TypeScript 5.0 重大更新解析',
                    source: 'ai_generated',
                    created_at: new Date().toISOString()
                },
                {
                    id: Date.now() + 3,
                    title: 'Node.js 性能优化最佳实践',
                    source: 'ai_generated',
                    created_at: new Date().toISOString()
                }
            ];
            
            topics.push(...fallbackTopics);
            res.json({ success: true, data: fallbackTopics });
        }
    } catch (error) {
        console.error('生成主题失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

app.post('/api/generate-article', async (req, res) => {
    try {
        console.log('收到生成文章请求:', req.body);
        
        const { topic, options } = req.body;
        
        // 构建详细的提示词
        const lengthMap = {
            short: '800-1200字',
            normal: '1500-2500字',
            long: '3000-4000字'
        };
        
        const styleMap = {
            professional: '专业严谨',
            accessible: '通俗易懂',
            humorous: '轻松幽默'
        };
        
        const targetLength = lengthMap[options.length] || '1500-2500字';
        const targetStyle = styleMap[options.style] || '专业严谨';
        const keywords = options.keywords && options.keywords.length > 0 ? options.keywords.join('、') : '';
        const includeCode = options.includeCode;
        
        const prompt = `请为微信公众号写一篇关于"${topic}"的技术文章。

要求：
1. 文章长度：${targetLength}
2. 写作风格：${targetStyle}
3. 目标读者：技术开发人员
4. 内容要求：
   - 包含详细的技术介绍和分析
   - 提供实际应用场景和案例
   - 结构清晰，逻辑性强
   - 语言准确，专业术语使用恰当
   ${includeCode ? '- 包含相关的代码示例和解释' : ''}
   ${keywords ? `- 重点涉及以下关键词：${keywords}` : ''}

文章结构建议：
1. 引言：简要介绍主题的重要性和文章概述
2. 核心内容：详细阐述技术要点（分2-3个主要部分）
3. 实践应用：提供具体的应用示例
4. 最佳实践：总结使用建议和注意事项
5. 总结：回顾要点并展望发展趋势

请确保文章内容充实，达到指定字数要求，并且具有较高的技术价值和可读性。`;

        try {
            const aiResponse = await callAI(prompt, settings.ai_provider, settings.api_key);
            
            // 将AI返回的文本转换为HTML格式
            const htmlContent = aiResponse
                .replace(/\n\n/g, '</p><p>')
                .replace(/^/, '<p>')
                .replace(/$/, '</p>')
                .replace(/## (.+)/g, '<h2>$1</h2>')
                .replace(/### (.+)/g, '<h3>$1</h3>')
                .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
                .replace(/\*(.+?)\*/g, '<em>$1</em>')
                .replace(/```([^`]+)```/g, '<pre><code>$1</code></pre>')
                .replace(/`([^`]+)`/g, '<code>$1</code>');
            
            // 计算字数（中文字符）
            const wordCount = aiResponse.replace(/[^\u4e00-\u9fa5]/g, '').length;
            
            const article = {
                title: topic,
                content: htmlContent,
                wordCount: wordCount
            };
            
            console.log(`AI生成文章成功，字数：${wordCount}`);
            res.json({ success: true, data: article });
            
        } catch (aiError) {
            console.error('AI生成文章失败，使用备用内容:', aiError);
            
            // 如果AI调用失败，返回更丰富的备用内容
            const fallbackContent = `
                <h1>${topic}</h1>
                <p>本文将深入探讨${topic}的相关技术要点，为技术开发人员提供全面的理解和实践指导。</p>
                
                <h2>技术概述</h2>
                <p>${topic}作为当前热门的技术领域，在现代软件开发中扮演着重要角色。它不仅提供了强大的功能特性，还为开发者带来了更高的开发效率和更好的用户体验。</p>
                <p>随着技术的不断发展，${topic}已经成为许多企业和开发团队的首选解决方案。本文将从多个角度分析其核心特性和应用价值。</p>
                
                <h2>核心特性分析</h2>
                <h3>高性能表现</h3>
                <p>在性能方面，${topic}采用了先进的优化策略，能够在各种场景下保持出色的运行效率。通过合理的架构设计和算法优化，它能够处理大规模的数据和复杂的业务逻辑。</p>
                
                <h3>开发效率提升</h3>
                <p>对于开发者而言，${topic}提供了丰富的开发工具和API接口，大大简化了开发流程。其直观的语法和完善的文档支持，使得新手也能快速上手。</p>
                
                <h3>扩展性和维护性</h3>
                <p>良好的模块化设计使得${topic}具备出色的扩展性。开发者可以根据项目需求灵活地添加或修改功能模块，同时保持代码的可维护性。</p>
                
                <h2>实际应用场景</h2>
                <p>在实际项目中，${topic}被广泛应用于以下场景：</p>
                <ul>
                    <li><strong>企业级应用开发</strong>：为大型企业提供稳定可靠的解决方案</li>
                    <li><strong>移动应用开发</strong>：支持跨平台开发，提高开发效率</li>
                    <li><strong>数据处理和分析</strong>：处理复杂的数据结构和分析需求</li>
                    <li><strong>云原生应用</strong>：适配现代云计算环境的部署需求</li>
                </ul>
                
                ${includeCode ? `
                <h2>代码示例</h2>
                <p>以下是一个基础的${topic}应用示例：</p>
                <pre><code>
// ${topic} 基础示例
function initializeApplication() {
    const config = {
        environment: 'production',
        debug: false,
        features: {
            optimization: true,
            caching: true
        }
    };
    
    // 初始化核心模块
    const app = new Application(config);
    
    // 配置中间件
    app.use(middleware.security());
    app.use(middleware.performance());
    
    // 启动应用
    app.start().then(() => {
        console.log('应用启动成功');
    }).catch(error => {
        console.error('启动失败:', error);
    });
    
    return app;
}

// 使用示例
const application = initializeApplication();
                </code></pre>
                ` : ''}
                
                <h2>最佳实践建议</h2>
                <h3>性能优化</h3>
                <p>在使用${topic}时，建议关注以下性能优化要点：</p>
                <ul>
                    <li>合理配置缓存策略，减少重复计算</li>
                    <li>优化数据结构，提高访问效率</li>
                    <li>使用异步处理，避免阻塞操作</li>
                </ul>
                
                <h3>安全考虑</h3>
                <p>安全性是${topic}应用中不可忽视的重要方面。开发者应该：</p>
                <ul>
                    <li>实施严格的输入验证和数据清理</li>
                    <li>使用安全的认证和授权机制</li>
                    <li>定期更新依赖库，修复安全漏洞</li>
                </ul>
                
                <h3>团队协作</h3>
                <p>在团队开发环境中，建议建立统一的编码规范和开发流程，确保代码质量和项目的可维护性。</p>
                
                <h2>发展趋势和展望</h2>
                <p>${topic}作为一个持续发展的技术领域，未来将在以下方面获得更大突破：</p>
                <ul>
                    <li><strong>智能化集成</strong>：与AI和机器学习技术的深度融合</li>
                    <li><strong>云原生支持</strong>：更好地适配容器化和微服务架构</li>
                    <li><strong>开发者体验</strong>：提供更加友好的开发工具和调试环境</li>
                    <li><strong>生态系统</strong>：构建更加完善的第三方插件和扩展体系</li>
                </ul>
                
                <h2>总结</h2>
                <p>通过本文的深入分析，我们可以看到${topic}在现代软件开发中的重要价值。它不仅提供了强大的技术能力，还为开发者带来了更高的效率和更好的开发体验。</p>
                <p>对于正在考虑采用${topic}的团队，建议从小规模项目开始实践，逐步积累经验，最终实现在大型项目中的成功应用。随着技术的不断成熟和生态系统的完善，${topic}必将在未来的技术发展中发挥更加重要的作用。</p>
                <p>希望本文能够为读者提供有价值的参考，并在实际项目中取得成功的应用效果。</p>
            `;
            
            const wordCount = fallbackContent.replace(/[^\u4e00-\u9fa5]/g, '').length;
            
            res.json({ 
                success: true, 
                data: {
                    title: topic,
                    content: fallbackContent,
                    wordCount: wordCount
                }
            });
        }
    } catch (error) {
        console.error('生成文章失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

// Helper function to parse inline formatting
function parseInlineFormatting(htmlText) {
    const runs = [];
    
    // Ensure htmlText is a string
    if (!htmlText || typeof htmlText !== 'string') {
        return [new TextRun({
            text: '',
            font: '微软雅黑',
            size: 22
        })];
    }
    
    let currentText = htmlText;
    
    // Process bold text
    const boldRegex = /<strong>(.*?)<\/strong>|\*\*(.*?)\*\*/g;
    const italicRegex = /<em>(.*?)<\/em>|\*(.*?)\*/g;
    const codeRegex = /<code>(.*?)<\/code>|`(.*?)`/g;
    
    // Simple approach: extract all formatting and create runs
    const parts = [];
    let lastIndex = 0;
    
    // Find all formatting tags
    const allMatches = [];
    let match;
    
    // Find bold matches
    while ((match = boldRegex.exec(htmlText)) !== null) {
        allMatches.push({
            type: 'bold',
            start: match.index,
            end: match.index + match[0].length,
            text: match[1] || match[2],
            fullMatch: match[0]
        });
    }
    
    // Find italic matches
    italicRegex.lastIndex = 0;
    while ((match = italicRegex.exec(htmlText)) !== null) {
        allMatches.push({
            type: 'italic',
            start: match.index,
            end: match.index + match[0].length,
            text: match[1] || match[2],
            fullMatch: match[0]
        });
    }
    
    // Find code matches
    codeRegex.lastIndex = 0;
    while ((match = codeRegex.exec(htmlText)) !== null) {
        allMatches.push({
            type: 'code',
            start: match.index,
            end: match.index + match[0].length,
            text: match[1] || match[2],
            fullMatch: match[0]
        });
    }
    
    // Sort matches by start position
    allMatches.sort((a, b) => a.start - b.start);
    
    // Build runs
    lastIndex = 0;
    for (const match of allMatches) {
        // Add text before this match
        if (match.start > lastIndex) {
            const beforeText = htmlText.substring(lastIndex, match.start);
            if (beforeText.trim()) {
                runs.push(new TextRun({
                    text: beforeText,
                    font: '微软雅黑',
                    size: 22
                }));
            }
        }
        
        // Add formatted text
        const runOptions = {
            text: match.text,
            font: match.type === 'code' ? 'Consolas' : '微软雅黑',
            size: match.type === 'code' ? 18 : 22
        };
        
        if (match.type === 'bold') {
            runOptions.bold = true;
        } else if (match.type === 'italic') {
            runOptions.italics = true;
        } else if (match.type === 'code') {
            runOptions.shading = { fill: 'F0F0F0' };
        }
        
        runs.push(new TextRun(runOptions));
        lastIndex = match.end;
    }
    
    // Add remaining text
    if (lastIndex < htmlText.length) {
        const remainingText = htmlText.substring(lastIndex);
        if (remainingText.trim()) {
            runs.push(new TextRun({
                text: remainingText,
                font: '微软雅黑',
                size: 22
            }));
        }
    }
    
    // If no formatting found, return simple text run
    if (runs.length === 0) {
        const plainText = htmlText.replace(/<[^>]*>/g, '');
        if (plainText.trim()) {
            runs.push(new TextRun({
                text: plainText,
                font: '微软雅黑',
                size: 22
            }));
        }
    }
    
    return runs;
}

app.post('/api/export-to-word', async (req, res) => {
    try {
        console.log('收到导出Word请求:', req.body);
        
        const { content, filename } = req.body;
        const filePath = path.join(__dirname, '..', 'exports', filename || '技术文章.docx');
        
        // 确保导出目录存在
        const exportDir = path.dirname(filePath);
        if (!fs.existsSync(exportDir)) {
            fs.mkdirSync(exportDir, { recursive: true });
        }
        
        // 使用docx库创建Word文档
        const { Document, Packer, Paragraph, TextRun, HeadingLevel } = require('docx');
        
        // 解析HTML内容并转换为docx格式
        console.log('Debug - content:', typeof content, content);
        const htmlContent = String(content.content || content || '');
        const title = String(content.title || '技术文章');
        console.log('Debug - htmlContent:', typeof htmlContent, htmlContent.length);
        
        // 检查是否有内容
        if (!htmlContent.trim()) {
            // 如果没有内容，创建一个包含提示信息的文档
            const doc = new Document({
                sections: [{
                    properties: {},
                    children: [
                        new Paragraph({
                            children: [
                                new TextRun({
                                    text: title,
                                    bold: true,
                                    size: 32,
                                    font: '微软雅黑'
                                })
                            ],
                            heading: HeadingLevel.TITLE,
                            spacing: { after: 400 }
                        }),
                        new Paragraph({
                            children: [
                                new TextRun({
                                    text: '此文档暂无内容。',
                                    font: '微软雅黑',
                                    size: 22,
                                    italics: true
                                })
                            ],
                            spacing: { after: 150 }
                        })
                    ]
                }]
            });
            
            const buffer = await Packer.toBuffer(doc);
            fs.writeFileSync(filePath, buffer);
            
            console.log('空内容Word文档导出成功:', filePath);
            res.json({ success: true, filePath: filePath });
            return;
        }
        
        // 简单的HTML解析逻辑
        const paragraphs = [];
        
        // 添加标题
        paragraphs.push(
            new Paragraph({
                children: [
                    new TextRun({
                        text: title,
                        bold: true,
                        size: 32,
                        font: '微软雅黑'
                    })
                ],
                heading: HeadingLevel.TITLE,
                spacing: { after: 400 }
            })
        );
        
        // 解析HTML内容
        const htmlLines = htmlContent
            .replace(/<[^>]*>/g, '\n')  // 移除HTML标签
            .split('\n')
            .map(line => line.trim())
            .filter(line => line.length > 0);
        
        // 重新解析HTML以保持格式 (支持多行内容)
        const htmlParts = htmlContent.split(/(<h[1-6][^>]*>[\s\S]*?<\/h[1-6]>|<p>[\s\S]*?<\/p>|<pre><code>[\s\S]*?<\/code><\/pre>|<ul>[\s\S]*?<\/ul>|<li>[\s\S]*?<\/li>)/g);
        
        for (const part of htmlParts) {
            if (!part.trim()) continue;
            
            if (part.match(/<h1[^>]*>(.*?)<\/h1>/)) {
                const text = part.replace(/<[^>]*>/g, '');
                paragraphs.push(
                    new Paragraph({
                        children: [
                            new TextRun({
                                text: text,
                                bold: true,
                                size: 28,
                                font: '微软雅黑'
                            })
                        ],
                        heading: HeadingLevel.HEADING_1,
                        spacing: { before: 400, after: 200 }
                    })
                );
            } else if (part.match(/<h2[^>]*>(.*?)<\/h2>/)) {
                const text = part.replace(/<[^>]*>/g, '');
                paragraphs.push(
                    new Paragraph({
                        children: [
                            new TextRun({
                                text: text,
                                bold: true,
                                size: 24,
                                font: '微软雅黑'
                            })
                        ],
                        heading: HeadingLevel.HEADING_2,
                        spacing: { before: 300, after: 150 }
                    })
                );
            } else if (part.match(/<h3[^>]*>(.*?)<\/h3>/)) {
                const text = part.replace(/<[^>]*>/g, '');
                paragraphs.push(
                    new Paragraph({
                        children: [
                            new TextRun({
                                text: text,
                                bold: true,
                                size: 20,
                                font: '微软雅黑'
                            })
                        ],
                        heading: HeadingLevel.HEADING_3,
                        spacing: { before: 200, after: 100 }
                    })
                );
            } else if (part.match(/<pre><code>[\s\S]*?<\/code><\/pre>/)) {
                const codeText = part.replace(/<[^>]*>/g, '').trim();
                // Split code into lines and create separate paragraphs for better formatting
                const codeLines = codeText.split('\n').filter(line => line.trim() || codeText.split('\n').indexOf(line) < codeText.split('\n').length - 1);
                
                for (const line of codeLines) {
                    paragraphs.push(
                        new Paragraph({
                            children: [
                                new TextRun({
                                    text: line || ' ', // Empty line placeholder
                                    font: 'Consolas',
                                    size: 18,
                                    color: '333333'
                                })
                            ],
                            spacing: { after: 50 },
                            indent: { left: 720 }, // Indent code blocks
                            shading: {
                                fill: 'F5F5F5'
                            }
                        })
                    );
                }
            } else if (part.match(/<p>[\s\S]*?<\/p>/)) {
                const htmlText = part.replace(/<\/?p>/g, '').trim();
                if (htmlText) {
                    const runs = parseInlineFormatting(htmlText);
                    paragraphs.push(
                        new Paragraph({
                            children: runs,
                            spacing: { after: 150 }
                        })
                    );
                }
            } else if (part.match(/<li>[\s\S]*?<\/li>/)) {
                const text = part.replace(/<[^>]*>/g, '').trim();
                if (text) {
                    // Handle bold text within list items
                    const runs = [];
                    const boldRegex = /\*\*(.*?)\*\*/g;
                    let lastIndex = 0;
                    let match;
                    
                    while ((match = boldRegex.exec(text)) !== null) {
                        // Add text before bold
                        if (match.index > lastIndex) {
                            runs.push(new TextRun({
                                text: text.substring(lastIndex, match.index),
                                font: '微软雅黑',
                                size: 22
                            }));
                        }
                        // Add bold text
                        runs.push(new TextRun({
                            text: match[1],
                            font: '微软雅黑',
                            size: 22,
                            bold: true
                        }));
                        lastIndex = match.index + match[0].length;
                    }
                    
                    // Add remaining text
                    if (lastIndex < text.length) {
                        runs.push(new TextRun({
                            text: text.substring(lastIndex),
                            font: '微软雅黑',
                            size: 22
                        }));
                    }
                    
                    // If no bold text found, use simple text
                    if (runs.length === 0) {
                        runs.push(new TextRun({
                            text: text,
                            font: '微软雅黑',
                            size: 22
                        }));
                    }
                    
                    paragraphs.push(
                        new Paragraph({
                            children: [
                                new TextRun({
                                    text: '• ',
                                    font: '微软雅黑',
                                    size: 22
                                }),
                                ...runs
                            ],
                            spacing: { after: 100 },
                            indent: { left: 360 }
                        })
                    );
                }
            }
        }
        
        // 如果没有解析到内容，使用纯文本处理
        if (paragraphs.length <= 1) {
            const plainText = htmlContent.replace(/<[^>]*>/g, '').trim();
            const lines = plainText.split('\n').filter(line => line.trim());
            
            for (const line of lines) {
                if (line.trim()) {
                    paragraphs.push(
                        new Paragraph({
                            children: [
                                new TextRun({
                                    text: line.trim(),
                                    font: '微软雅黑',
                                    size: 22
                                })
                            ],
                            spacing: { after: 150 }
                        })
                    );
                }
            }
        }
        
        // 创建Word文档
        const doc = new Document({
            sections: [{
                properties: {},
                children: paragraphs
            }]
        });
        
        // 生成文档缓冲区
        const buffer = await Packer.toBuffer(doc);
        
        // 写入文件
        fs.writeFileSync(filePath, buffer);
        
        console.log('Word文档导出成功:', filePath);
        res.json({ success: true, filePath: filePath });
        
    } catch (error) {
        console.error('导出Word失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

app.post('/api/save-article', async (req, res) => {
    try {
        console.log('收到保存文章请求:', req.body);
        
        const article = req.body;
        article.id = Date.now().toString();
        article.created_at = new Date().toISOString();
        articles.push(article);
        
        res.json({ success: true, data: article });
    } catch (error) {
        console.error('保存文章失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

app.get('/api/article-history', async (req, res) => {
    try {
        const limit = parseInt(req.query.limit) || 50;
        const result = articles.slice(-limit).reverse();
        res.json({ success: true, data: result });
    } catch (error) {
        console.error('获取历史记录失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

app.get('/api/settings', async (req, res) => {
    try {
        res.json({ success: true, data: settings });
    } catch (error) {
        console.error('获取设置失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

app.post('/api/save-settings', async (req, res) => {
    try {
        console.log('收到保存设置请求:', req.body);
        
        const newSettings = req.body;
        settings = { ...settings, ...newSettings };
        
        res.json({ success: true, data: settings });
    } catch (error) {
        console.error('保存设置失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

app.get('/api/topics', async (req, res) => {
    try {
        const limit = parseInt(req.query.limit) || 20;
        const result = topics.slice(-limit).reverse();
        res.json({ success: true, data: result });
    } catch (error) {
        console.error('获取主题失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

app.post('/api/save-topic', async (req, res) => {
    try {
        console.log('收到保存主题请求:', req.body);
        
        const topic = req.body;
        topic.id = Date.now().toString();
        topic.created_at = new Date().toISOString();
        topics.push(topic);
        
        res.json({ success: true, data: topic });
    } catch (error) {
        console.error('保存主题失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

app.get('/api/article/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const article = articles.find(a => a.id === id);
        if (article) {
            res.json({ success: true, data: article });
        } else {
            res.status(404).json({ success: false, error: '文章未找到' });
        }
    } catch (error) {
        console.error('获取文章失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

app.delete('/api/article/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const index = articles.findIndex(a => a.id === id);
        if (index !== -1) {
            articles.splice(index, 1);
            res.json({ success: true });
        } else {
            res.status(404).json({ success: false, error: '文章未找到' });
        }
    } catch (error) {
        console.error('删除文章失败:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`AI2Word 简化服务器运行在 http://localhost:${PORT}`);
    console.log('开发模式: 在浏览器中打开上述地址');
});

module.exports = app;